﻿(function ($) {
    $.fn.yqNForeignKey = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqNForeignKey.methods[opts](this, param);
        }

        return this.each(function () {
            var $this = $(this);
            var opt;
            if ($this.data("yqtype") == "yqNForeignKey") {
                var $uniqueID = $this.attr("ID");
                var opts_ = $.extend({}, options($this));
                destroy($this);
                $this = $("#" + $uniqueID);
                opt = $.extend(opts_, opts);
            }
            else {
                opt = $.extend({}, $.fn.yqNForeignKey.defaults, opts);
                var $uniqueID = $this.attr("ID");
                if ($uniqueID === undefined || $uniqueID === null || $uniqueID == "") {
                    $uniqueID = $.getUniqueID();
                    $this.attr("ID", $uniqueID);
                }
            }

            $this.html("");

            if (opt.width === undefined) {
                opt.width = $this.width();
            }

            opt.rows = [];

            //组件加载结束
            opt.onload = true;
            //组件进程执行中
            opt.running = false;

            opt.firstShowPanel = false;

            //变量信息
            $this.data("nforeignkey_opt", opt);
            $this.data("yqtype", "yqNForeignKey");

            if (opt.displayType == 2) {
                opt.row = {};
            }

            initui($this);
        });
    };

    $.fn.yqNForeignKey.defaults = {
        ajaxUrl: "/_db.html", //ajax地址

        //width: 200,
        panelWidth: 600,
        panelHeight: 280,

        displayType: 2,                 //显示类型, 1--下拉列表 2--查询窗体
        dbname: "yqbase",               //数据库
        tbname: "",                     //表
        tempno: 100,                    //实例 
        addWhere: "",                   //额外条件
        order: "",                     //排序

        isPage: true,                   //分页
        pageSize: 10,
        pageNo: 1,
        pageList: [5, 10, 20, 30, 40, 50],

        valueMember: "sid",             //值字段
        displayMember: "sid",          //显示字段

        titles: [],                     //数据列配置对象

        expandMember: null,              //扩展查询字段,用“,”分割（用于下拉列表模式）

        isSeek: true,                    //弹窗查询
        seekNo: -1,                      //查询模板编码  displayType=2生效
        seekModeW: 800,                  //模态编辑器宽度 格式为 800（数字）
        seekModeH: 600,                  //模态编辑器高度 格式为 600（数字）
        //用于查询窗体
        seekSimple: true,     //简单查询
        seekSimpleDDLW: 150,  //条件宽度
        seekSimpleTxtW: 200,  //条件宽度

        enable: true,                    //是否可用，默认可用

        beforeBindingTitle: function (columns, callback) {
            callback(columns);
        },

        onClickRow: function (rows) { },  //选择行事件 null：为空
    };

    $.fn.yqNForeignKey.methods = {
        options: function (jq) {
            return options($(jq[0]));
        },
        destroy: function (jq) {
            destroy($(jq[0]));
        },
        disable: function (jq) {
            enable($(jq[0]), false);
        },
        enable: function (jq) {
            enable($(jq[0]), true);
        },
        addWhere: function (jq, value) {
            options($(jq[0])).addWhere = value;
        },
        setValue: function (jq, value) {
            setValue($(jq[0]), value);
        },
        getValue: function (jq) {
            return getValue($(jq[0]));
        },
        setRows: function (jq, row) {
            setRows($(jq[0]), row);
        },
        getRows: function (jq) {
            return getRows($(jq[0]));
        },
        clear: function (jq) {
            var $object = $(jq[0]);
            setValue($object, null);
        },
        resize: function (jq, width) {
            resize($(jq[0]), width);
        }
    };

    function options($object) {
        return $object.data("nforeignkey_opt");
    }

    function resize($object, width) {
        var opt = options($object);

        if (opt === undefined) {
            $object.width(width);
        }
        else {
            if (opt.displayType == 1) {
                $object.combogrid("resize", width);
            }
            else {
                $object.textbox("resize", width);
            }
        }

        enable($object, opt.enable);
    }

    function destroy($object) {
        var opt = options($object);
        var $new_obj = $($object.prop("outerHTML"));
        $new_obj.show();
        var id = $object.attr("id");
        $new_obj.removeAttr("id");
        $new_obj.removeClass("textbox-f");
        $new_obj.removeClass("combo-f");
        $new_obj.removeClass("combogrid-f");
        $object.before($new_obj);

        $object.textbox("destroy");

        $new_obj.attr("id", id);

        $object.removeData("nforeignkey_opt");
        $object.removeData("yqtype");
    }

    function enable($object, tf) {
        var opt = options($object);

        opt.enable = tf;

        var $text = $object.next().find(".textbox-text");

        var btn_mub = 3;

        var $icon0 = $object.textbox("getIcon", 0);
        var $icon1 = $object.textbox("getIcon", 1);
        if (opt.enable) {
            $icon0.show();
            $icon1.show();

            btn_mub = 2;
        } else {
            $icon0.hide();
            $icon1.hide();
            btn_mub = 0;
        }

        if (opt.enable) {
            $text.removeAttr("disabled");
        } else {
            $text.attr("disabled", "true");
        }


        opt.width = $object.next().width();
        $text.css({
            "margin": "0px " + (26 * btn_mub) + "px 0px 0px",
            "width": (opt.width - (26 * btn_mub)) + "px"
        });
    }

    function initui($object) {
        var opt = options($object);

        var opt_txt = {
            width: opt.width,
            icons: [{
                iconCls: 'icon-clear',
                handler: function (e) {
                    opt.rows = [];
                    $(e.data.target).textbox("setValue", "");

                    opt.onClickRow.call($object, null);
                }
            }, {
                iconCls: 'icon2-down',
                handler: function (e) {
                    get_select($object);
                }
            }]
        }

        $object.textbox(opt_txt);
        $object.next().find(".textbox-text").attr("readonly", true);

        opt.onload = false;

        $object.textbox("options").onResize = function (width, height) {
            opt.width = width;
            enable($object, opt.enable);
        };


        enable($object, opt.enable);
    }

    function get_select($object) {
        var opt = options($object);

        var $txt = $object.next().find(".textbox-text");
        prevent_e = $.getPreventDefault($txt[0]);
        prevent_e.id = $object.attr("id");
        prevent_e.options = opt;

        var mdiinfo = $.yqGetWindParams();

        var run_opt = {
            ajaxUrl: opt.ajaxUrl,
            mdiinfo: mdiinfo,
            prevent_e: prevent_e,

            dbname: opt.dbname,                   //数据库
            tbname: opt.tbname,                   //表
            tempno: opt.tempno,                   //实例 
            addWhere: opt.addWhere,               //额外条件
            order: opt.order,                     //排序

            width: opt.panelWidth,
            height: opt.panelHeight,

            isPage: opt.isPage,                   //分页
            pageSize: opt.pageSize,
            pageNo: opt.pageNo,
            pageList: opt.pageList,

            seekSimple: opt.seekSimple,             //简单查询
            seekSimpleDDLW: opt.seekSimpleDDLW,     //条件宽度
            seekSimpleTxtW: opt.seekSimpleTxtW,     //条件宽度

            isSeek: opt.isSeek,
            seekNo: opt.seekNo,                     //查询模板编码  displayType=2生效
            seekModeW: opt.seekModeW,               //模态编辑器宽度 格式为 800（数字）
            seekModeH: opt.seekModeH,               //模态编辑器高度 格式为 600（数字）

            choiceOne: false,                        // true 单选,false 多选
            valueMember: opt.valueMember,             //值字段
            displayMember: opt.displayMember,
            defaultValue: getValue($object),

            callback: function (rows) {
                if ($object.data("yqtype") === undefined) {
                    var ed = $.yqTextEditor(opt.p_target, opt.p_field);
                    if (!(ed === null)) {
                        $(ed.target).yqNForeignKey('setRows', rows);
                        opt.onClickRow.call($(ed.target), rows);
                    }
                } else {
                    setRows($object, rows);
                    opt.onClickRow.call($object, rows);
                }
            },
        };
        if (window.top == window.self) {
            $.yqRowsPopSelect(run_opt);
        }
        else {
            window.top.$.yqRowsPopSelect(run_opt);
        }
    }

    function setValue($object, value) {
        var opt = options($object);

        if (!opt.onload) {
            setValueRun($object, value);
        }
        else {
            setTimeout(function () {
                setValue($object, value);
            }, 500);
        }

    }

    function setValueRun($object, value) {
        var opt = options($object);

        opt.rows = [];
        opt.running = true;
        $object.textbox("setText", "");

        if (value === undefined || value === null || value == "") {
            return;
        }

        var where_ = "";
        var ids_ = value.split(",");
        for (let i = 0; i < ids_.length; i++) {
            where_ += (where_ == "" ? "" : ",") + "'" + ids_[i] + "'";
        }

        $.yqDbTbSelect({
            url: opt.ajaxUrl,
            dbname: opt.dbname,
            tbname: opt.tbname,
            where: opt.valueMember + " in (" + where_ + ")",
            order: ""
        }, function (data) {
            if (data.error == 0) {
                setRows($object, data.rows)
            } else {
                console.log(data)
            }

            opt.running = false;
        });

    }

    function getValue($object) {
        var opt = options($object);

        if (opt.rows.length == 0) {
            return null;
        }

        var value_ = "";

        for (let i = 0; i < opt.rows.length; i++) {
            value_ += (value_ == "" ? "" : ",") + opt.rows[i][opt.valueMember];
        }

        if (value_ == "") {
            return null;
        } else {
            return value_;
        }
    }

    function setRows($object, rows) {
        var opt = options($object);
        opt.rows = rows;
        if (rows.length == 0) {
            $object.textbox("setText", "");
        } else {
            var text_ = "";
            for (let i = 0; i < rows.length; i++) {
                text_ += (text_ == "" ? "" : ",") + rows[i][opt.displayMember];

            }
            $object.textbox("setText", text_);
        }
    }

    function getRows($object) {
        var opt = options($object);
        return opt.rows;
    }
})(jQuery);